package gov.child.web.exception;

import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

/**
 * @author fzh
 * @since 2017/9/18
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ModelAndView notFound(NullPointerException e) {
        logger.error(e);
        return new ModelAndView("notFound");
    }

    @ExceptionHandler({MultipartException.class, IOException.class})
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    @ResponseBody
    public ModelAndView uploadFailed(MultipartException f, IOException io) {
        if (f != null) logger.error(f);
        if (io != null) logger.error(io);
        return new ModelAndView("error_happened");
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView error_happened(RuntimeException e){
        logger.error(e);
        return new ModelAndView("error_happened");
    }
}
